<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class ApiLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{
            $m = [];
            $m['method'] = $request->method();
            $m['remoteUser'] = $request->user()?$request->user()->id:0;
            $m['requestURI'] = $request->getRequestUri();
            $m['requestURL'] = $request->url();
            $m['contentType'] = $request->getContentType();
            $m['parameter'] = json_encode($request->all());
            $m['protocol'] = $request->server('SERVER_PROTOCOL');
            $m['scheme'] = $request->getScheme();
            $m['serverName'] = $request->server('SERVER_NAME');
            $m['serverPort'] = $request->server('SERVER_PORT');
            $m['remoteAddr'] = $request->server('REMOTE_ADDR');
            $m['remoteHost'] = array_key_exists( 'REMOTE_HOST', $_SERVER) ? $_SERVER['REMOTE_HOST'] : gethostbyaddr($_SERVER["REMOTE_ADDR"]);
            $m['localAddr'] = $request->getHttpHost();
            $m['createTime'] = time();
            DB::table('api_log')->insert($m);
        }catch (\Exception $e){
            Log::error($e->getMessage());
        }

        return $next($request);
    }
}
